package com.hunantv.mglive.ui.discovery.publisher.pic;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.hunantv.mglive.R;
import com.hunantv.mglive.utils.AlbumConstants;
import com.hunantv.mglive.utils.AlbumUtil;
import com.hunantv.mglive.utils.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class AlbumListActivity extends Activity {
	public static final int MAX_RECENT_PHOTO_NUM = 100;
	public static final String RECENT_PHOTO_SELECT_CLAUSE = Images.ImageColumns.SIZE + ">0" + ") GROUP BY ("
			+ Images.Media.DATA;
	
	private ListView mListView;
	private AlbumListViewAdapter mListAdapter;
	//private ArrayList<String> mSelectList;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_albumlist);
        init();
	}

	private void init() {
		Button cancel = (Button) findViewById(R.id.cancel);
		cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		//mRootPath = Environment.getExternalStorageDirectory().getAbsolutePath();
		mListView = (ListView) findViewById(R.id.albumlist);
		mListAdapter = new AlbumListViewAdapter(this);
		mListView.setAdapter(mListAdapter);
		
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				QQAlbumInfo info = mListAdapter.getItem(position);
				if (info == null || info.imageCount <= 0 || TextUtils.isEmpty(info.name)) {
					Toast.makeText(AlbumListActivity.this, "相册为空！", Toast.LENGTH_SHORT).show();
					return;
				}
				Intent intent = getIntent();
				intent.putExtra("albumid", info._id);
				intent.putExtra("albumname", info.name);
				
				intent.setClass(AlbumListActivity.this, PicChooserUI.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
				setResult(RESULT_OK,intent);
				finish();
//				startActivity(intent);
//				AlbumUtil.anim(AlbumListActivity.this, true, true);
			}
		});
		
		
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
	}

	@Override
	public void onResume() {
		super.onResume();
		AsyncTask<Object, Object, List<QQAlbumInfo>> queryAlbumTask = new AsyncTask<Object, Object, List<QQAlbumInfo>>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showProgressDialog();
			}

			@Override
			protected List<QQAlbumInfo> doInBackground(Object... params) {
				List<QQAlbumInfo> albumList = getAllAlbumList();
				return albumList;
			}

			@Override
			protected void onPostExecute(List<QQAlbumInfo> result) {
				cancelProgressDialog();
				updateList(result);
			}
		};
		
		List<QQAlbumInfo> systemAlbumList = AlbumUtil.getCacheBuckets();
		if (systemAlbumList == null || lastModifiedTime < AlbumUtil.getCacheLastModify()) {
			queryAlbumTask.execute("");
		} else {
			updateList(getAllAlbumList());
		}
	}

	private void updateList(List<QQAlbumInfo> result) {
		mListAdapter.setData(result);
		
		mListAdapter.notifyDataSetChanged();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onDestroy() {
		mListAdapter.mActivity = null;
		super.onDestroy();
	}


	private boolean isCameraDir(String name) {
		if (name == null)
			return false;
		String cameraString = name.toLowerCase();
		if (cameraString.equalsIgnoreCase("camera"))
			return true;
		if (cameraString.equalsIgnoreCase("100media"))
			return true;
		return false;
	}
	
	static long lastModifiedTime;
	private List<QQAlbumInfo> getAllAlbumList() {

		List<QQAlbumInfo> systemAlbumList = AlbumUtil.getCacheBuckets();
		if (systemAlbumList == null || lastModifiedTime < AlbumUtil.getCacheLastModify()) {
			systemAlbumList = AlbumUtil.queryBuckets(this, 0, true);
			if (systemAlbumList != null) {
				sortBucketArray(systemAlbumList);

				QQAlbumInfo recentAlbum = AlbumUtil.getCacheRecentBucket();
				// how to do if photo are too many
				if (recentAlbum == null) {
					recentAlbum = AlbumUtil
							.queryRecentBucket(getApplicationContext(), AlbumConstants.RECENT_PHOTO_MIN_WIDTH,
									AlbumListActivity.MAX_RECENT_PHOTO_NUM, true);
				}
				if (recentAlbum.cover != null && recentAlbum.cover.path != null && recentAlbum.cover.path.length() > 0) {
					systemAlbumList.add(0, recentAlbum);
				}
			}
			lastModifiedTime = AlbumUtil.getCacheLastModify();
		}
		return systemAlbumList;
	}
	
	private void sortBucketArray(List<QQAlbumInfo> bucketList) {
		if (bucketList == null)
			return;

		int N = bucketList.size();
		List<QQAlbumInfo> cameraAlbumList = new ArrayList<QQAlbumInfo>();
		for (int i = 0; i < N; i++) {
			QQAlbumInfo bucketInfo = bucketList.get(i);
			if (isCameraDir(bucketInfo.name)) {
				cameraAlbumList.add(bucketInfo);

			}
		}
		bucketList.removeAll(cameraAlbumList);
		Collections.sort(bucketList, sBucketComparator);
		Collections.sort(cameraAlbumList, sBucketComparator);
		bucketList.addAll(0, cameraAlbumList);
	}

	
	private Dialog pd;

	private void showProgressDialog() {
//		try {
//			if (pd != null) {
//				cancelProgressDialog();
//			} else {
//				pd = new Dialog(this, R.style.qZoneInputDialog);
//				pd.setCancelable(true);
//				pd.show();
//				pd.setContentView(R.layout.photo_preview_progress_dialog);
//			}
//			if (!pd.isShowing()) {
//				pd.show();
//			}
//		} catch (Exception e) {
//			pd = null;
//		}
	}

	private void cancelProgressDialog() {
		try {
			if (pd != null) {
				pd.cancel();
			}
		} catch (Exception e) {
			pd = null;
		}
	}
	
	private Comparator<QQAlbumInfo> sBucketComparator = new Comparator<QQAlbumInfo>() {
		@Override
		public int compare(QQAlbumInfo object1, QQAlbumInfo object2) {
			Long lhs = Long.valueOf(object1.coverDate);
			Long rhs = Long.valueOf(object2.coverDate);
			return -lhs.compareTo(rhs);
		}
	};

}
